//
//  LBFeedItemModel.m
//  look.book
//
//  Created by Chih Yuan Liu on 3/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LBFeedItemModel.h"
#import "LBFeedItem.h"

@implementation LBFeedItemModel

@synthesize delegate;

int const MAX_FEEDS_COUNT = 50;

- (void)requestSucceeded {
	NSString *responseString = [[NSString alloc] initWithData:recievedData encoding:NSUTF8StringEncoding];
	NSArray * result = [parser parse:responseString];
	NSMutableArray * diffs = [[NSMutableArray alloc] init];
	for(LBFeedItem * item in result){
		NSUInteger index = [keys indexOfObject:item.link];
		if(index == NSNotFound){
			[feeds insertObject:item atIndex:0];
			[diffs insertObject:item atIndex:0];
			[keys insertObject:item.link atIndex:0];
            if([feeds count] > MAX_FEEDS_COUNT){
                int remove_index = [feeds count]-1;
                [feeds removeObjectAtIndex:remove_index];
                [keys removeObjectAtIndex:remove_index];
            }
		}
        [item release];
	}
    //[responseString release];
	[delegate fetcherSucceeded: self updates:diffs];
	[delegate fetcherEnd:self];
    [diffs release];
}

-(void)requestFailed:(NSError*)error {
	[delegate fetcherFailed:self];
	[delegate fetcherEnd:self];
}

-(id) initWithDelegate:(NSObject<LBFeedItemDelegate>*)_delegate{
    self = [super init];
	if(self){
		parser = [[FeedParser alloc] init];
		feeds = [[NSMutableArray alloc] init];
		keys = [[NSMutableArray alloc] init];
		delegate  = _delegate;
		[self refresh];
	}
	return self;
}

-(void) refresh{
	NSString * url = @"http://lookbook.nu/rss";
	[super requestGET:url];
	[delegate fetcherBegin:self];
}

-(NSInteger) GetCount{
	if(feeds!=nil){
		return [feeds count];
	}else {
		return 0;
	}

}

-(LBFeedItem*) GetItemAtIndex:(int)index{
	if(feeds!=nil){
		return [feeds objectAtIndex:index];
	}else {
		return nil;
	}
}

-(void) removeFromModel:(LBFeedItem*)item{
	
}

@end
